<?php
require('common.php');


// catch form submission and redirect
if (!empty($_POST))
{
	$P = array_map(mysql_real_escape_string, $_POST);
	$name = $P['english_nm'];
	$user = user();
	
	$sql = "SELECT * FROM Definitions WHERE English_Name='$name' AND (User='$user' OR User IS NULL)";
	$result = mysql_query($sql) or die("could not $sql: " . mysql_error());
	$already_defined = mysql_num_rows($result);
	
	if ($name == '' || $already_defined > 0)
	{
		// throw an error message 
		if ($name == '')
		{
			$error = "Please provide a name for this function.";
		} else {
			$error = "A function with this name has already been defined.  Please choose a different name.";
		}
			$error = '<h4>' . $error . '</h4>' . "\n";
	} else {
		// save this fxn and redirect to main
		$fxn_call = $user . time();
		
		$sql = "INSERT INTO Definitions SET English_Name='$name', ";
		
		for ($i = 0; $i < count($vars); $i++)
		{
			$var_name = $P[$vars[$i]];
			
			// if fields were left blank, leave variable fields as NULL
			if (!empty($var_name))
			{
				$sql .= $vars[$i] . "='$var_name', ";
			}
		}
		
		if (!empty($P['returns_to']))
		{
			$return = $P['returns_to'];
			$sql .= "Returns_To='$return', ";
		}
		
		if (!empty($P['description']))
		{
			$desc = $P['description'];
			$sql .= "Description='$desc', ";
		}
		
		
		$sql .= "Fxn_Call='$fxn_call', User='$user' ";
		
		mysql_query($sql) or die("unable to $sql: " . mysql_error());
		
		// also create dummy variable
		sql_exec("INSERT INTO Variables SET User='$user', Domain='$fxn_call'");
		
		// add the variables to Variables
		for ($i = 0; $i < count($vars); $i++)
		{
			$var_name = $P[$vars[$i]];
			
			// if fields were left blank, leave variable fields as NULL
			// the variable should be converted to something nice (deterministic fxn) 
			// upon compilation
			if (!empty($var_name))
			{
				$sql = "INSERT INTO Variables SET User='$user', Domain='$fxn_call', Name='$var_name'";
				sql_exec($sql);
			}
		}
		
		header("Location: edit_page.php?domain=$fxn_call");
	}
}

function argument_fields()
{
	$vars2 = array("Parameter 1"=>"Var1", "Parameter 2"=>"Var2", "Parameter 3"=>"Var3", "Parameter 4"=>"Var4", "Parameter 5"=>"Var5", "Parameter 6"=>"Var6");
	foreach ($vars2 as $user_name=>$true_name)
	{
		echo '<tr>
<td>' . $user_name . ' (If Applicable)</td>
<td><input type="text" name="' . $true_name . '" /></td>
</tr>';
	}
}

html_header("add a page");

?>

<body>

<div id="container">

<?php header_div(); ?>

<div id="body">

<h4>add a page</h4>

<?php echo $error; ?>

<form action="add_domain.php" method="post">

<table>
<tr>
<td>name</td>
<td><input type="text" name="english_nm" /></td>
</tr>

<?php //argument_fields(); ?>

<tr>
<td>description</td>
<td><textarea name="description" rows="5" cols="45"></textarea></td>
</tr>

</table>

<p><input type="submit" value="add" /></p>

</form>

<?php echo footer(); ?>

</div>

</div>
</body>
</html>
